//var rootCas = require('ssl-root-cas/latest').create();
const https = require('https');
//https.globalAgent.options.ca = rootCas;

const appInfo = {
    APP_ID: "makelouden",
    APP_KEY: "k5J7xWLzRFlLqFjB6yF7jwEtlhrNfuVs",
    REDIRECT_URI: "http://edu.makelouden.cc/user/setToken/shanghaiedu",
    REDIRECT_URI2: "http://edu.makelouden.cc/user/codeLogin/shanghaiedu"
}

const setToken = (req, res, cb) => {
    /*
    http://editor.makelouden.cc/user/setToken/qq?code=106F95F473BF91CF118C5903DE2583EC&state=vJRzivds2C7BzUTEd6ZyOY2i5-DLsq8g
    */
    var code = req.query.code;
    var path = "/oauth/token?grant_type=authorization_code&code=" + code + "&client_id=" + appInfo.APP_ID + "&client_secret=" + appInfo.APP_KEY + "&redirect_uri=" + appInfo.REDIRECT_URI;

    // console.log(path);
    var options = {
        hostname: "oau.shec.edu.cn",
        port: 443,
        method: 'POST',
        path: path,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        rejectUnauthorized: false
    };
    var req1 = https.request(options, (res1) => {
        // console.log('statusCode:', res1.statusCode);
        // console.log('headers:', res1.headers);
        res1.on('data', (d) => {
            // console.log('BODY: ' + d);
            d = JSON.parse(d);
            let getUserInfo = () => {
                path = "/rest/user/getLoggedInUser?access_token=" + d.access_token;
                // console.log(path);
                options = {
                    hostname: "oau.shec.edu.cn",
                    port: 443,
                    method: 'GET',
                    path: path,
                    rejectUnauthorized: false
                };
                var req2 = https.request(options, (res2) => {
                    res2.on('data', (d2) => {
                        // console.log('BODY2: ' + d2);
                        d2 = JSON.parse(d2);
                        var sessionStore = req.sessionStore;
                        var sid = req.query.state;
                        sessionStore.load(sid, function (err, sess) {
                            if (err) {
                                res.redirect(301, '/close.html');
                                console.error(err);
                            } else if (!sess) {
                                res.redirect(301, '/close.html');
                            } else if (d2.errcode) {
                                // console.log(d2);
                                res.send(JSON.stringify({
                                    result: -1,
                                    msg: "登陆错误，请重试",
                                    // error: error
                                }));
                                console.error(errcode);
                            } else {
                                sess.userInfo = {
                                    userType: "shanghaiedu",
                                    id: "shanghaiedu_" + d2.id,
                                    nickname: d2.name,
                                    verified: true,
                                    // prop: d2
                                };
                                sess.save((err) => {
                                    if (err) {
                                        console.error(err);
                                    }
                                });
                                res.redirect(301, '/close.html');
                                // console.log("set token\n" + sess.id + "\n" + sess);
                                cb(sess.userInfo);
                            }
                        });
                    });
                });
                req2.on('error', (err) => {
                    // console.error(e);
                    res.send(JSON.stringify({
                        result: -1,
                        msg: "获取用户信息出错",
                        // error: e
                    }));
                    console.error(err);
                });
                req2.end();
            };
            getUserInfo();
        });
    });
    req1.on('error', (err) => {
        res.send(JSON.stringify({
            result: -1,
            msg: "登陆错误，请重试",
            // error: e
        }));
        console.error(err);
    });
    req1.end();
};


const codeLogin = (req, res, cb) => {
    var code = req.query.code;
    var path = "/oauth/token?grant_type=authorization_code&code=" + code + "&client_id=" + appInfo.APP_ID + "&client_secret=" + appInfo.APP_KEY + "&redirect_uri=" + appInfo.REDIRECT_URI2;

    // console.log(path);
    var options = {
        hostname: "oau.shec.edu.cn",
        port: 443,
        method: 'POST',
        path: path,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        rejectUnauthorized: false
    };
    var req1 = https.request(options, (res1) => {
        // console.log('statusCode:', res1.statusCode);
        // console.log('headers:', res1.headers);
        res1.on('data', (d) => {
            // console.log('BODY: ' + d);
            d = JSON.parse(d);

            let getUserInfo = () => {
                path = "/rest/user/getLoggedInUser?access_token=" + d.access_token;
                // console.log(path);
                options = {
                    hostname: "oau.shec.edu.cn",
                    port: 443,
                    method: 'GET',
                    path: path,
                    rejectUnauthorized: false
                };
                var req2 = https.request(options, (res2) => {
                    res2.on('data', (d2) => {
                        // console.log('BODY2: ' + d2);
                        d2 = JSON.parse(d2);
                        if (d2.errcode) {
                            // console.log(d2);
                            res.send(JSON.stringify({
                                result: -1,
                                msg: "登陆错误，请重试"
                            }));
                            console.error(errcode);
                        } else {
                            var userInfo = {
                                userType: "shanghaiedu",
                                id: "shanghaiedu_" + d2.id,
                                nickname: d2.name,
                                verified: true,
                                // prop: d2
                            };
                            req.session.userInfo = userInfo;
                            cb(userInfo);
                            res.redirect(301, '/index.html');
                        }
                    });
                });
                req2.on('error', (err) => {
                    res.send(JSON.stringify({
                        result: -1,
                        msg: "获取用户信息出错",
                    }));
                    console.error(err);
                });
                req2.end();
            };
            getUserInfo();
        });
    });
    req1.on('error', (err) => {
        // console.error(e);
        res.send(JSON.stringify({
            result: -1,
            msg: "登陆错误，请重试"
        }));
        console.error(err);
    });
    req1.end();
};

module.exports = { setToken, codeLogin }